<?php

namespace app\admin\controller;

use think\exception\ValidateException;
use app\model\Goods;
use app\model\Category;
use app\model\GoodsDescription;
use app\model\GoodsImage;
use app\model\GoodsSku;
use app\model\GoodsSkuValue;
use app\model\GoodsShareCharges;
use app\model\Store;
use app\model\Config;
use app\model\MemberAuthGroup;
use app\model\GoodsMemberDiscount;
use app\model\Operatingcity;
use app\model\Area;

class GoodsController extends Base
{

    function index()
    {
        $uniacid = uniacid();
        $page = input('post.page', 1, 'intval');
        $keyword = input('post.keyword', '', 'serach_in');
        $cat_id = input('post.cat_id', '', 'serach_in');
        $ptype = input('post.ptype', '', 'serach_in');
        $is_recommand = input('post.is_recommand', '', 'serach_in');
        $status = input('post.status', '', 'serach_in');
        $query = Goods::where(['uniacid' => $uniacid]);

        if (!empty($ptype)) {
            $query->where('ptype', $ptype);
        } else {
            $query->where('ptype', '>', 0);
        }
        if (!empty($this->sid)) {
            $query->where('sid', $this->sid);
        }
        if (!empty($this->ocid)) {
            $Operatingcitydata = Operatingcity::find($this->ocid);
            if ($Operatingcitydata) {
                $Operatingcitydata = $Operatingcitydata->toArray();
                if ($Operatingcitydata['areatype'] == 2) {
                    $query->where('district_name', $Operatingcitydata['district_name']);
                } elseif ($Operatingcitydata['areatype'] == 1) {
                    $query->where('city_name', $Operatingcitydata['city_name']);
                }
            }
        }

        if (!empty($keyword)) {
            $query->where('name', 'like', '%' . $keyword . '%');
        }

        if (!empty($cat_id)) {
            $query->where('cat_id', $cat_id);
        }

        if (!empty($is_recommand) || $is_recommand === "0") {
            $query->where('is_recommand', $is_recommand);
        }

        if (!empty($status) || $status === "0") {
            $query->where(['status' => $status]);
        }

        $res = $query->order('sort asc,id desc')
            ->paginate(getpage())
            ->toArray();

        foreach ($res['data'] as &$vo) {
            $vo['image'] = toimg($vo['image']);
            if ($vo['sid'] == 0) {
                $vo['name'] = '[自营]' . $vo['name'];
            } else {
                $StoreTitle = Store::getTitle($vo['sid']);
                if (empty($StoreTitle)) {
                    $vo['name'] = '[商户已被删除]' . $vo['name'];
                } else {
                    $vo['name'] = '[' . $StoreTitle . ']' . $vo['name'];
                }
            }
            $vo['cat_id'] = Category::getTitle($vo['cat_id']);
            $vo['create_time'] = time_format($vo['create_time']);
            $vo['update_time'] = time_format($vo['update_time']);
        }
        $data['data'] = $res;
        if ($page == 1) {
            $data['field_data']['cidarray'] = _generateSelectTree(Category::getpcarray());
        }
        return $this->json($data);
    }

    function listUpdate()
    {
        $data = only('id,is_recommand,is_additional,status,sort');
        if (!$data['id']) throw new ValidateException('参数错误');
        Goods::update($data);
        return $this->json(['msg' => '操作成功']);
    }

    public function update()
    {
        $id = request()->post('id');
        $data = input('post.');
        $data['update_time'] = time();
        $data['image'] = $data['images'][0]['url'];

        if ($data['cat_id']) {
            $cat = Category::find($data['cat_id']);
            if (!empty($cat)) {
                $cat = $cat->toArray();
            }
            $data['ptype'] = $cat['ptype'];
            $data['deliverymode'] = $cat['deliverymode'];
        }
        if (!empty($data['videourl'])) {
            $data['videotype'] = 1;
        } elseif (!empty($data['videoid'])) {
            $data['videotype'] = 2;
        } else {
            $data['videotype'] = 0;
        }
        if (isset($data['sku'])) {
            foreach ($data['sku'] as $index => $skuarr) {
                if ($skuarr['price']) {
                    if ($index == 0) {
                        $data['price'] = $skuarr['price'];
                    }
                    $data['price'] = min($data['price'], $skuarr['price']);
                }
            }

        }

        if (empty($id)) {
            $data['uniacid'] = uniacid();
            $data['create_time'] = time();
            if (!empty($this->sid)) {
                $data['sid'] = $this->sid;

                $storemod = Store::find($this->sid);
                if ($storemod) {
                    $data['province_name'] = $storemod->province_name;
                    $data['city_name'] = $storemod->city_name;
                    $data['district_name'] = $storemod->district_name;
                }
            }
            if (!empty($this->ocid)) {
                $data['ocid'] = $this->ocid;
                if (!empty($this->ocid)) {
                    $ocmod = Operatingcity::find($this->ocid);
                    if ($ocmod) {
                        $data['province_name'] = $ocmod->province_name;
                        $data['city_name'] = $ocmod->city_name;
                        $data['district_name'] = $ocmod->district_name;
                    }
                }
            }


            if (empty($data['tel'])) {
                $data['tel'] = '';
            }


            try {
                $res = Goods::create($data);
                if ($res->id && empty($data['sort'])) {
                    Goods::update(['sort' => $res->id, 'id' => $res->id]);
                }
                $data['id'] = $res->id;
                $this->_synupdata($data);
            } catch (\Exception $e) {
                throw new ValidateException($e->getMessage());
            }
            return $this->json(['msg' => '添加成功', 'data' => $res->id]);
        } else {
            try {
                Goods::update($data);
                $this->_synupdata($data);
            } catch (\Exception $e) {
                throw new ValidateException($e->getMessage());
            }
            return $this->json(['msg' => '修改成功']);
        }
    }

    function _synupdata($data)
    {
        //详情
        if (empty(GoodsDescription::where('goods_id', $data['id'])->find())) {
            GoodsDescription::create([
                'goods_id' => (int)$data['id'],
                'description' => $data['description']
            ]);
        } else {
            GoodsDescription::where('goods_id', $data['id'])->update(['description' => $data['description']]);
        }

        //sku

        GoodsSku::where('goods_id', $data['id'])->delete();
        if (isset($data['attribute'])) {
            foreach ($data['attribute'] as $attr) {
                GoodsSku::create([
                    'goods_id' => (int)$data['id'],
                    'name' => $attr['name'],
                    'ptype' => 'radio',
                    'item' => implode(',', $attr['item'])
                ]);
            }
        }

        GoodsSkuValue::where('goods_id', $data['id'])->delete();
        if (isset($data['sku'])) {
            foreach ($data['sku'] as $skuarr) {
                GoodsSkuValue::create([
                    'goods_id' => (int)$data['id'],
                    'sku' => $skuarr['sku'],
                    'image' => $skuarr['image'],
                    'quantity' => $skuarr['quantity'],
                    'price' => $skuarr['price']
                ]);
            }
        }

        GoodsShareCharges::where('goods_id', $data['id'])->delete();
        if (!empty($data['is_share_charges']) && !empty($data['sharecharges'])) {
            foreach ($data['sharecharges'] as $scvo) {
                if ($scvo['price'] > 0) {
                    GoodsShareCharges::create([
                        'goods_id' => (int)$data['id'],
                        'level' => $scvo['level'],
                        'price' => (float)$scvo['price'],
                        'charges_method' => (int)$data['charges_method']
                    ]);
                }
            }
        }

        GoodsMemberDiscount::where('goods_id', $data['id'])->delete();
        if (!empty($data['is_member_discount']) && !empty($data['MemberGroup'])) {
            foreach ($data['MemberGroup'] as $mgvo) {
                if ($mgvo['price'] > 0) {
                    GoodsMemberDiscount::create([
                        'goods_id' => (int)$data['id'],
                        'mgid' => (int)$mgvo['id'],
                        'price' => (float)$mgvo['price']
                    ]);
                }
            }
        }
        //图片
        GoodsImage::where('goods_id', $data['id'])->delete();
        if (isset($data['images'])) {
            foreach ($data['images'] as $image) {
                GoodsImage::create([
                    'goods_id' => (int)$data['id'],
                    'uniacid' => uniacid(),
                    'image' => $image['url']
                ]);
            }
        }
    }

    function getgoodssku()
    {
        $id = $this->request->post('id', '', 'serach_in');
        $data['attribute'] = GoodsSku::get_goods_sku($id);
        $data['sourceAttribute'] = $data['attribute'];
        return $this->json(['data' => $data]);
    }

    function getInfo()
    {
        $id = $this->request->post('id', '', 'serach_in');
        //if (!$id) throw new ValidateException('参数错误');
        if ($id) {
            $data = Goods::field('*')->find($id)->toArray();
        } else {
            $data = [
                'is_times' => 0,
                'sort' => 100,
                'status' => 1,
            ];
        }

        $GD = GoodsDescription::where(['goods_id' => $id])->find();

        if (!empty($GD)) {
            $data['description'] = $GD->description;
        }

        $goods_image = GoodsImage::where(['goods_id' => $id])
            ->field('image')
            ->order('id asc')
            ->select()->toArray();

        if (!empty($goods_image)) {
            foreach ($goods_image as $key => $vo) {
                $data['images'][$key]['url'] = toimg($vo['image']);
            }
        }

        $data['attribute'] = GoodsSku::get_goods_sku($id);
        $data['sourceAttribute'] = $data['attribute'];

        $MGDiscountarray = GoodsMemberDiscount::where(['goods_id' => $id])->select()->toArray();

        if (!empty($MGDiscountarray)) {
            $MGDiscount = [];
            foreach ($MGDiscountarray as $vo) {
                $MGDiscount[$vo['mgid']] = $vo['price'];
            }
        }

        $data['MemberGroup'] = MemberAuthGroup::getGroup();
        foreach ($data['MemberGroup'] as &$mvo) {
            if (!empty($MGDiscount[$mvo['id']])) {
                $mvo['price'] = $MGDiscount[$mvo['id']];
            }
        }


        $data['sku'] = GoodsSkuValue::field('sku,image,quantity,price')->where(['goods_id' => $id])
            ->order('id asc')
            ->select()->toArray();

        $data['sharelevel'] = (int)Config::getconfig('agent')['level'];

        $sharechargesarray = GoodsShareCharges::where(['goods_id' => $id])->select()->toArray();

        if (!empty($sharechargesarray)) {
            foreach ($sharechargesarray as $vo) {
                $sharecharges[$vo['level']]['price'] = $vo['price'];
            }
        }

        for ($i = 1; $i <= $data['sharelevel']; $i++) {
            $data['sharecharges'][$i]['price'] = $sharecharges[$i]['price'];
            $data['sharecharges'][$i]['level'] = $i;
            if ($i == 1) {
                $data['sharecharges'][$i]['title'] = '一层佣金';
                $data['sharecharges'][$i]['help_block'] = '注：一层为顾客的直接上级（如果开启分销内购,分销商自己购买商品，享受一层佣金）';
            }
            if ($i == 2) {
                $data['sharecharges'][$i]['title'] = '二层佣金';
                $data['sharecharges'][$i]['help_block'] = '注：二层为顾客的上上级';
            }
            if ($i == 3) {
                $data['sharecharges'][$i]['title'] = '一层佣金';
                $data['sharecharges'][$i]['help_block'] = '注：三层为顾客的上上上级';
            }
        }

        if (empty($data['bout_card_date'])) {
            $data['bout_card_date'] = '';
        }
        return $this->json(['data' => $data]);
    }

    function delete()
    {
        $idx = $this->request->post('id', '', 'serach_in');
        if (!$idx) throw new ValidateException('参数错误');
        Goods::destroy(['id' => explode(',', $idx)], true);
        return $this->json(['msg' => '操作成功']);
    }

    function getField()
    {
        $ptype = input('post.ptype');
        $data['cidarray'] = _generateSelectTree(Category::getpcarray($ptype));
        return $this->json(['data' => $data]);
    }
}
